<?php
/**
 * @Author: hpp
 * @Date:   2018-12-04 17:57:46
 * @Last Modified by:   hpp
 * @Last Modified time: 2018-12-05 18:07:03
 */
namespace app\admin\controller;

use think\Request;
use app\admin\model\Menu;

class SysMenu extends BaseController
{
    /**
     * 显示
     *
     * @return \think\Response
     */
    public function index(Request $request)
    {   
        $breadcrumb = $this->breadcrumb;
        if (intval($request->id)) {
            $menu = Menu::getMenuNameById($request->id);
            $breadcrumb = '<li>系统设置</li><li><a href="/admin/sysmenu">系统菜单</a></li><li class="active"><strong>'.$menu.'</strong></li>';
            $this->assign('breadcrumb',$breadcrumb);
        }
        $where['parent_id'] = intval($request->id) ? $request->id : 0;
        $list = Menu::where($where)->order(['weight' => 'desc','id' => 'desc'])->paginate(30);
        $this->assign('p_id',$request->id ? $request->id : 0);
        return $this->fetch('sysmenu/index',compact('list'));
    }

    /**
     * 保存
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $param = parse_str(input('post.data'),$data);
        if (intval(input('post.id'))) {
            $res = $this->validate($data,'app\admin\validate\Meun.edit');
        }else{
            $res = $this->validate($data,'app\admin\validate\Meun.add');
        }
        if (true !== $res) {
            return json(['code' => 0,'msg' => $res]);
        }
        if (intval(input('post.id'))) {
            $res = Menu::where('id',intval(input('post.id')))->update($data);
            $msg = $res ? '修改成功' :'修改失败';
        }else{
            $res = Menu::create($data);
            $msg = $res ? '添加成功' :'添加失败';
        }
        if ($res) {
            return json(['code' => 1,'msg' => $msg]);
        }else{
            return json(['code' => 0,'msg' => $msg]);
        }
    }

    /**
     * 显示
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        $data = Menu::field('id,parent_id,name,icon,permission_key,url,weight,desc')->find(intval($id));
        return json(['code' =>1, 'data' => $data]);
    }

    /**
     * 更新菜单显示隐藏状态
     */
    public function updateStatus($id,$status)
    {
        if (!in_array($status, [0,1])) {
            return json(['code' => 0,'msg' => '状态错误']);
        }
        $status = $status == 0 ? 1 : 0;
        $res = Menu::where('id',$id)->update(['status' => $status]);
        $res and Menu::where('parent_id',$id)->update(['status' => $status]);
        if (!$res) {
            return json(['code' => 0,'msg' => '操作失败']);
        }
        return json(['code' => 1,'msg' => '操作成功']);
    }
}
